<template>
  <div class="mbti-test-container">
    <van-nav-bar
      title="MBTI职业测评"
      left-arrow
      @click-left="handleBack"
    />
    
    <!-- 测试未开始状态 -->
    <div v-if="testStatus.status === TEST_STATUS.NOT_STARTED" class="start-section">
      <div class="welcome-card">
        <h2>欢迎参加MBTI职业测评</h2>
        <p class="intro-text">本测试将帮助你了解自己的性格类型，并为你推荐合适的职业发展方向。</p>
        <div class="test-info">
          <div class="info-item">
            <van-icon name="clock-o" />
            <span>预计用时：15-20分钟</span>
          </div>
          <div class="info-item">
            <van-icon name="question-o" />
            <span>题目数量：93题</span>
          </div>
          <div class="info-item">
            <van-icon name="info-o" />
            <span>测试说明：请根据真实想法选择最符合的选项</span>
          </div>
        </div>
        <button class="start-btn" @click="startTest">开始测试</button>
      </div>
    </div>

    <!-- 测试进行中状态 -->
    <div v-else-if="testStatus.status === TEST_STATUS.IN_PROGRESS" class="test-section">
      <div class="progress-container">
        <div class="progress-info">
          <div class="progress-text">
            <span class="current">问题 {{ testStatus.answeredQuestions + 1 }}</span>
            <span class="total">/ {{ testStatus.totalQuestions }}</span>
          </div>
          <div class="dimension-progress">
            <div v-for="dimension in dimensions" 
                 :key="dimension.key"
                 class="dimension-progress-item"
                 :class="{ active: currentQuestion.dimension === dimension.key }">
              <div class="dimension-label">{{ dimension.name }}</div>
              <div class="dimension-bar">
                <div class="dimension-fill" 
                     :style="{ width: `${getDimensionProgress(dimension.key)}%` }">
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="progress-bar">
          <div class="progress" 
               :style="{ width: `${(testStatus.answeredQuestions / testStatus.totalQuestions) * 100}%` }">
          </div>
        </div>
      </div>

      <div class="question-card">
        <div class="question-header">
          <div class="question-meta">
            <span class="question-number">问题 {{ currentQuestion.id }}</span>
            <span class="dimension-tag" :class="currentQuestion.dimension">
              {{ getDimensionName(currentQuestion.dimension) }}
            </span>
          </div>
          <div class="question-context" v-if="currentQuestion.context">
            {{ currentQuestion.context }}
          </div>
        </div>
        
        <div class="question-content">
          <h2 class="question-text">{{ currentQuestion.question }}</h2>
          <div class="question-description" v-if="currentQuestion.description">
            {{ currentQuestion.description }}
          </div>
          
          <div class="options" :class="{ 'likert-scale': isLikertScale(currentQuestion) }">
            <template v-if="isLikertScale(currentQuestion)">
              <div class="likert-labels">
                <span>完全不符合</span>
                <span>不太符合</span>
                <span>一般</span>
                <span>比较符合</span>
                <span>非常符合</span>
              </div>
              <div class="likert-options">
                <button
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  class="likert-option"
                  :class="{ 
                    selected: selectedOption === option,
                    'previous-answer': currentQuestion.previousAnswer === option
                  }"
                  @click="selectOption(option)"
                >
                  {{ index + 1 }}
                </button>
              </div>
            </template>
            <template v-else>
              <button
                v-for="(option, index) in currentQuestion.options"
                :key="index"
                class="option-btn"
                :class="{ 
                  selected: selectedOption === option,
                  'previous-answer': currentQuestion.previousAnswer === option
                }"
                @click="selectOption(option)"
              >
                {{ option }}
              </button>
            </template>
          </div>
        </div>

        <div class="question-footer" v-if="currentQuestion.isReversed">
          <van-icon name="info-o" />
          <span>注：此题采用反向计分</span>
        </div>
      </div>

      <div class="navigation">
        <button
          v-if="testStatus.answeredQuestions > 0"
          class="nav-btn secondary"
          @click="showResetConfirm"
        >
          重新开始
        </button>
        <button
          class="nav-btn primary"
          :disabled="!selectedOption"
          @click="submitAnswer"
        >
          {{ testStatus.answeredQuestions === testStatus.totalQuestions - 1 ? '完成测试' : '下一题' }}
        </button>
      </div>
    </div>

    <!-- 测试结果状态 -->
    <div v-else-if="testStatus.status === TEST_STATUS.COMPLETED" class="results-section">
      <div class="result-card">
        <h2>MBTI 测试结果</h2>
        <div class="mbti-type">{{ mbtiResult.type }}</div>
        <div class="type-description">{{ mbtiResult.description }}</div>
        
        <div class="dimension-analysis">
          <div v-for="(dimension, key) in mbtiResult.dimensions" 
               :key="key" 
               class="dimension">
            <h3>{{ getDimensionName(key) }}</h3>
            <div class="dimension-score">
              <div class="score-bar">
                <div class="score-fill" 
                     :style="{ 
                       width: `${dimension.scores.percentage[dimension.dominant]}%`,
                       backgroundColor: getDimensionColor(getDimensionName(key))
                     }">
                </div>
              </div>
              <div class="score-labels">
                <span>{{ key[0] }}</span>
                <span>{{ key[1] }}</span>
              </div>
            </div>
            <p class="dimension-description">{{ dimension.analysis.content }}</p>
          </div>
        </div>

        <div class="career-suggestions">
          <h3>职业发展建议</h3>
          <div class="career-grid">
            <div v-for="(item, index) in mbtiResult.analysis.career.items" 
                 :key="index"
                 class="career-item">
              <van-icon name="star" class="career-icon" />
              <span>{{ item }}</span>
            </div>
          </div>
        </div>

        <div class="action-buttons">
          <button class="action-btn secondary" @click="resetTest">
            重新测试
          </button>
          <button class="action-btn primary" @click="startCareerMatch">
            查看详细职业分析
          </button>
        </div>
      </div>
    </div>

    <!-- 添加调试信息 -->
    <div v-if="showCareerMatch" style="padding: 10px; background: #f0f0f0; margin: 10px; border-radius: 4px;">
      <p>Debug Info:</p>
      <p>showCareerMatch: {{ showCareerMatch }}</p>
      <p>hasCareerMatchData: {{ hasCareerMatchData }}</p>
      <p>careerMatch exists: {{ !!careerMatch }}</p>
      <p v-if="careerMatch">
        personalityTraits: {{ careerMatch.personalityTraits?.length || 0 }} items<br>
        careerMatches: {{ careerMatch.careerMatches?.length || 0 }} items<br>
        developmentSuggestions: {{ careerMatch.developmentSuggestions?.length || 0 }} items
      </p>
    </div>

    <!-- 修改职业匹配分析状态的显示逻辑 -->
    <div v-if="showCareerMatch" class="career-match-section">
      <div v-if="!hasCareerMatchData" class="loading-state">
        <p>正在加载职业匹配分析...</p>
      </div>
      <div v-else class="career-match-card">
        <h2>职业匹配分析</h2>
        
        <div v-if="careerMatch?.personalityTraits?.length" class="personality-traits">
          <h3>性格特征分析</h3>
          <div v-for="(trait, index) in careerMatch.personalityTraits" 
               :key="index" 
               class="trait-item">
            <h4>{{ trait.title }}</h4>
            <p>{{ trait.description }}</p>
          </div>
        </div>

        <div v-if="careerMatch?.careerMatches?.length" class="career-matches">
          <h3>推荐职业</h3>
          <div v-for="(match, index) in careerMatch.careerMatches" 
               :key="index" 
               class="match-item">
            <div class="match-header">
              <h4>{{ match.title }}</h4>
              <span class="match-level" :class="match.level">
                {{ match.level }}匹配度
              </span>
            </div>
            <p class="match-description">{{ match.description }}</p>
            <div class="match-details">
              <div v-if="match.requiredSkills?.length" class="skills">
                <h5>所需技能</h5>
                <ul>
                  <li v-for="(skill, skillIndex) in match.requiredSkills" 
                      :key="skillIndex">
                    {{ skill }}
                  </li>
                </ul>
              </div>
              <div v-if="match.prospects" class="prospects">
                <h5>发展前景</h5>
                <p>{{ match.prospects }}</p>
              </div>
              <div v-if="match.challenges" class="challenges">
                <h5>潜在挑战</h5>
                <p>{{ match.challenges }}</p>
              </div>
            </div>
          </div>
        </div>

        <div v-if="careerMatch?.developmentSuggestions?.length" class="development-suggestions">
          <h3>发展建议</h3>
          <div v-for="(suggestion, index) in careerMatch.developmentSuggestions" 
               :key="index" 
               class="suggestion-item">
            <h4>{{ suggestion.title }}</h4>
            <p>{{ suggestion.description }}</p>
          </div>
        </div>

        <div class="action-buttons">
          <button class="action-btn secondary" @click="resetTest">
            重新测试
          </button>
          <button class="action-btn primary" @click="showCareerMatch = false">
            返回结果
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { showDialog, showToast } from 'vant';
import { TEST_STATUS } from '../services/mbtiService';

const router = useRouter();
const sessionId = ref(Date.now().toString());
const testStatus = ref({ status: TEST_STATUS.NOT_STARTED });
const currentQuestion = ref(null);
const selectedOption = ref(null);
const mbtiResult = ref(null);
const careerMatch = ref(null);
const showCareerMatch = ref(false);

// 添加防抖标志
const isSubmitting = ref(false);

const dimensions = [
  { key: 'EI', name: '外向-内向' },
  { key: 'SN', name: '感觉-直觉' },
  { key: 'TF', name: '思考-情感' },
  { key: 'JP', name: '判断-知觉' }
];

// 获取维度名称
const getDimensionName = (dimension) => {
  const names = {
    'EI': '外向-内向',
    'SN': '感觉-直觉',
    'TF': '思考-情感',
    'JP': '判断-知觉'
  };
  return names[dimension] || dimension;
};

// 获取维度标签
const getDimensionLabel = (name, isFirst) => {
  const labels = {
    '外向-内向': isFirst ? 'E' : 'I',
    '感觉-直觉': isFirst ? 'S' : 'N',
    '思考-情感': isFirst ? 'T' : 'F',
    '判断-知觉': isFirst ? 'J' : 'P'
  };
  return labels[name] || '';
};

// 获取维度颜色
const getDimensionColor = (name) => {
  const colors = {
    '外向-内向': '#4CAF50',
    '感觉-直觉': '#2196F3',
    '思考-情感': '#FF9800',
    '判断-知觉': '#9C27B0'
  };
  return colors[name] || '#666';
};

// 获取相反值
const getOppositeValue = (value) => {
  const opposites = {
    'E': 'I',
    'I': 'E',
    'S': 'N',
    'N': 'S',
    'T': 'F',
    'F': 'T',
    'J': 'P',
    'P': 'J'
  };
  return opposites[value] || value;
};

// 判断是否为李克特量表问题
const isLikertScale = (question) => {
  return question.options.length === 5 && 
         question.options.every(opt => 
           ['非常符合', '比较符合', '一般', '不太符合', '完全不符合'].includes(opt)
         );
};

// 获取维度进度
const getDimensionProgress = (dimension) => {
  const total = testStatus.value.totalQuestions;
  const answered = testStatus.value.answeredQuestions;
  const dimensionQuestions = testStatus.value.dimensionProgress?.[dimension] || 0;
  return (dimensionQuestions / total) * 100;
};

// 开始测试
const startTest = async () => {
  try {
    let controller = new AbortController();
    let timeoutId = setTimeout(() => {
      controller.abort('请求超时，请稍后重试');
    }, 120000);

    const response = await fetch('/api/mbti-test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        sessionId: sessionId.value,
        action: 'start'
      }),
      signal: controller.signal
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || '开始测试失败');
    }

    const data = await response.json();
    if (!data.success) {
      throw new Error(data.error || '开始测试失败');
    }

    if (data.data.type === 'mbti_test') {
      // 更新测试状态
      testStatus.value = data.data.content.testStatus;
      // 更新当前问题
      if (data.data.content.question) {
        currentQuestion.value = data.data.content.question;
        // 确保测试状态为 in_progress
        testStatus.value.status = TEST_STATUS.IN_PROGRESS;
      }
    }
  } catch (error) {
    console.error('开始测试失败:', error);
    showDialog({
      title: '错误',
      message: error.message || '开始测试失败，请稍后重试'
    });
  }
};

// 选择选项
const selectOption = (option) => {
  selectedOption.value = option;
};

// 提交答案
const submitAnswer = async () => {
  if (!currentQuestion.value) {
    console.error('没有当前问题');
    return;
  }

  // 防止重复提交
  if (isSubmitting.value) {
    showToast('请稍候...');
    return;
  }

  try {
    isSubmitting.value = true;
    console.log('开始提交答案:', {
      sessionId: sessionId.value,
      questionNumber: currentQuestion.value.id,
      selectedOption: selectedOption.value
    });

    const response = await fetch('/api/mbti-test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        sessionId: sessionId.value,
        questionNumber: currentQuestion.value.id,
        answer: selectedOption.value,
        action: 'answer'
      })
    });

    // 检查响应状态
    if (!response.ok) {
      const errorText = await response.text();
      console.error('服务器响应错误:', errorText);
      throw new Error('提交答案失败，请重试');
    }

    // 尝试解析 JSON
    let data;
    try {
      data = await response.json();
    } catch (e) {
      console.error('JSON 解析错误:', e);
      throw new Error('服务器响应格式错误，请重试');
    }

    console.log('服务器响应数据:', data);

    if (!data.success) {
      throw new Error(data.error || '提交答案失败');
    }

    // 处理测试完成的情况
    if (data.data.type === 'mbti_result') {
      console.log('测试完成，显示结果:', data.data.content);
      testStatus.value = {
        status: TEST_STATUS.COMPLETED,
        currentQuestion: null,
        totalQuestions: testStatus.value.totalQuestions,
        answeredQuestions: testStatus.value.totalQuestions
      };
      mbtiResult.value = data.data.content;
      return;
    }

    // 处理继续测试的情况
    if (data.data.type === 'mbti_test') {
      // 检查是否已完成所有问题
      if (testStatus.value.answeredQuestions + 1 >= testStatus.value.totalQuestions) {
        console.log('已完成所有问题，等待结果');
        showToast('正在生成测评报告...');
        return;
      }

      console.log('获取到下一个问题:', {
        questionId: data.data.content.question.id,
        currentQuestion: data.data.content.testStatus.currentQuestion,
        totalQuestions: data.data.content.testStatus.totalQuestions
      });

      // 验证问题数据
      if (!data.data.content.question || !data.data.content.question.id || !data.data.content.question.question || !data.data.content.question.options) {
        console.error('问题数据不完整:', data.data.content.question);
        throw new Error('问题数据不完整');
      }

      // 更新测试状态和当前问题
      const currentStatus = testStatus.value;
      testStatus.value = {
        status: TEST_STATUS.IN_PROGRESS,
        currentQuestion: data.data.content.question.id,
        totalQuestions: data.data.content.testStatus.totalQuestions,
        answeredQuestions: currentStatus.answeredQuestions + 1,
        dimensionProgress: currentStatus.dimensionProgress || {},
        lastAnsweredQuestion: data.data.content.question.id
      };
      
      // 确保问题数据完整
      const nextQuestion = {
        id: data.data.content.question.id,
        question: data.data.content.question.question,
        options: data.data.content.question.options,
        dimension: data.data.content.question.dimension,
        context: data.data.content.question.context,
        description: data.data.content.question.description,
        isReversed: data.data.content.question.isReversed,
        previousAnswer: selectedOption.value
      };

      console.log('更新测试状态:', testStatus.value);
      console.log('更新当前问题:', nextQuestion);

      currentQuestion.value = nextQuestion;
      selectedOption.value = null; // 重置选项
    } else {
      console.error('未知的响应类型:', data.data.type);
      throw new Error('未知的响应类型');
    }
  } catch (error) {
    console.error('提交答案时发生错误:', error);
    showDialog({
      title: '错误',
      message: error.message || '提交答案失败，请重试'
    });
  } finally {
    // 重置提交状态
    setTimeout(() => {
      isSubmitting.value = false;
    }, 500); // 添加 500ms 的冷却时间
  }
};

// 重置测试
const resetTest = async () => {
  try {
    let controller = new AbortController();
    let timeoutId = setTimeout(() => {
      controller.abort('请求超时，请稍后重试');
    }, 120000);

    const response = await fetch('/api/mbti-test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        sessionId: sessionId.value,
        action: 'reset'
      }),
      signal: controller.signal
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || '重置测试失败');
    }

    const data = await response.json();
    if (!data.success) {
      throw new Error(data.error || '重置测试失败');
    }

    testStatus.value = data.data.content.testStatus;
    currentQuestion.value = data.data.content.question;
    selectedOption.value = null;
    mbtiResult.value = null;
    careerMatch.value = null;
    showCareerMatch.value = false;
  } catch (error) {
    console.error('重置测试失败:', error);
    showDialog({
      title: '错误',
      message: error.message || '重置测试失败，请稍后重试'
    });
  }
};

// 开始职业匹配分析
const startCareerMatch = async () => {
  try {
    console.log('开始获取职业匹配分析，MBTI类型:', mbtiResult.value?.type);
    
    if (!mbtiResult.value?.type) {
      console.error('MBTI类型未定义');
      throw new Error('无法获取MBTI类型');
    }

    let controller = new AbortController();
    let timeoutId = setTimeout(() => {
      controller.abort('请求超时，请稍后重试');
    }, 120000);

    const requestBody = {
      mbtiType: mbtiResult.value.type
    };
    console.log('发送请求体:', requestBody);

    const response = await fetch('/api/career-match', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody),
      signal: controller.signal
    });

    clearTimeout(timeoutId);

    console.log('收到响应状态:', response.status);
    
    if (!response.ok) {
      const errorData = await response.json();
      console.error('服务器返回错误:', errorData);
      throw new Error(errorData.error || '获取职业匹配分析失败');
    }

    const data = await response.json();
    console.log('收到响应数据:', data);

    if (!data.success) {
      console.error('响应数据表示失败:', data);
      throw new Error(data.error || '获取职业匹配分析失败');
    }

    if (!data.data?.content?.analysis) {
      console.error('响应数据缺少必要字段:', data);
      throw new Error('职业匹配分析数据格式错误');
    }

    const analysis = data.data.content.analysis;
    console.log('解析后的分析数据:', analysis);

    // 验证分析数据的结构
    if (!analysis.personalityTraits || !Array.isArray(analysis.personalityTraits)) {
      console.error('性格特征数据格式错误:', analysis.personalityTraits);
      throw new Error('性格特征数据格式错误');
    }

    if (!analysis.careerMatches || !Array.isArray(analysis.careerMatches)) {
      console.error('职业匹配数据格式错误:', analysis.careerMatches);
      throw new Error('职业匹配数据格式错误');
    }

    if (!analysis.developmentSuggestions || !Array.isArray(analysis.developmentSuggestions)) {
      console.error('发展建议数据格式错误:', analysis.developmentSuggestions);
      throw new Error('发展建议数据格式错误');
    }

    // 设置数据前先清空旧数据
    careerMatch.value = null;
    showCareerMatch.value = false;
    
    // 等待下一个 tick
    await nextTick();
    
    // 设置新的分析数据
    careerMatch.value = analysis;
    console.log('设置后的careerMatch数据:', careerMatch.value);
    
    // 再次等待下一个 tick
    await nextTick();
    
    // 确保显示职业匹配分析
    showCareerMatch.value = true;
    console.log('职业匹配分析显示状态:', showCareerMatch.value);

    // 验证数据是否正确设置
    nextTick(() => {
      console.log('DOM更新后的careerMatch数据:', careerMatch.value);
      console.log('DOM更新后的显示状态:', showCareerMatch.value);
      console.log('hasCareerMatchData值:', hasCareerMatchData.value);
    });
  } catch (error) {
    console.error('获取职业匹配分析失败:', error);
    showDialog({
      title: '错误',
      message: error.message || '获取职业匹配分析失败，请稍后重试'
    });
  }
};

// 修改 hasCareerMatchData 计算属性，添加更详细的日志
const hasCareerMatchData = computed(() => {
  const hasData = careerMatch.value && 
         Array.isArray(careerMatch.value.personalityTraits) &&
         Array.isArray(careerMatch.value.careerMatches) &&
         Array.isArray(careerMatch.value.developmentSuggestions);
  
  console.log('hasCareerMatchData computed:', {
    careerMatchExists: !!careerMatch.value,
    personalityTraits: careerMatch.value?.personalityTraits?.length,
    careerMatches: careerMatch.value?.careerMatches?.length,
    developmentSuggestions: careerMatch.value?.developmentSuggestions?.length,
    result: hasData
  });
  
  return hasData;
});

// 添加监听器来追踪数据变化
watch(careerMatch, (newValue) => {
  console.log('careerMatch数据变化:', newValue);
}, { deep: true });

watch(showCareerMatch, (newValue) => {
  console.log('showCareerMatch状态变化:', newValue);
});

// 显示重置确认对话框
const showResetConfirm = () => {
  showDialog({
    title: '确认重新开始',
    message: '重新开始将清除所有已答题目，确定要继续吗？',
    showCancelButton: true
  }).then(() => {
    resetTest();
  });
};

// 返回上一页
const handleBack = () => {
  if (testStatus.value.status === TEST_STATUS.IN_PROGRESS) {
    showDialog({
      title: '确认退出',
      message: '测试尚未完成，确定要退出吗？',
      showCancelButton: true
    }).then(() => {
      router.back();
    });
  } else {
    router.back();
  }
};

// 检查是否有未完成的测试
onMounted(() => {
  // 初始化时只设置状态为未开始，不调用 API
  testStatus.value = { status: TEST_STATUS.NOT_STARTED };
});
</script>

<style scoped>
.mbti-test-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 20px;
}

/* 开始测试部分 */
.start-section {
  padding: 20px;
}

.welcome-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.welcome-card h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 16px;
}

.intro-text {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 24px;
}

.test-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.start-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 12px 32px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.start-btn:hover {
  background: #45a049;
}

/* 测试进行中部分 */
.test-section {
  padding: 20px;
}

.progress-container {
  background: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-info {
  margin-bottom: 16px;
}

.progress-text {
  display: flex;
  justify-content: center;
  align-items: baseline;
  margin-bottom: 16px;
}

.progress-text .current {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.progress-text .total {
  font-size: 16px;
  color: #666;
  margin-left: 4px;
}

.dimension-progress {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.dimension-progress-item {
  text-align: center;
}

.dimension-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.dimension-bar {
  height: 4px;
  background: #e0e0e0;
  border-radius: 2px;
  overflow: hidden;
}

.dimension-fill {
  height: 100%;
  background: #4CAF50;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.dimension-progress-item.active .dimension-fill {
  background: #2196F3;
}

.question-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.question-header {
  margin-bottom: 20px;
}

.question-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-context {
  font-size: 14px;
  color: #666;
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 8px;
}

.question-content {
  margin-bottom: 20px;
}

.question-description {
  font-size: 14px;
  color: #666;
  margin: 12px 0;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 8px;
}

.likert-scale {
  margin-top: 24px;
}

.likert-labels {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 12px;
  color: #666;
}

.likert-options {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.likert-option {
  flex: 1;
  height: 40px;
  border: 2px solid #e0e0e0;
  border-radius: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
  color: #333;
}

.likert-option:hover {
  border-color: #4CAF50;
  background: #f9f9f9;
}

.likert-option.selected {
  border-color: #2E7D32;
  background: #C8E6C9;
  color: #1B5E20;
  font-weight: bold;
}

.likert-option.previous-answer {
  border-color: #FFA000;
  background: #FFF3E0;
  color: #E65100;
}

.question-footer {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
  padding: 12px;
  background: #fff3e0;
  border-radius: 8px;
}

.dimension-tag {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
}

.dimension-tag.EI {
  background: #e8f5e9;
  color: #4CAF50;
}

.dimension-tag.SN {
  background: #e3f2fd;
  color: #2196F3;
}

.dimension-tag.TF {
  background: #fff3e0;
  color: #FF9800;
}

.dimension-tag.JP {
  background: #f3e5f5;
  color: #9C27B0;
}

.navigation {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.nav-btn {
  flex: 1;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-btn.primary {
  background: #4CAF50;
  color: white;
}

.nav-btn.primary:hover:not(:disabled) {
  background: #45a049;
}

.nav-btn.secondary {
  background: #f5f5f5;
  color: #666;
}

.nav-btn.secondary:hover {
  background: #e0e0e0;
}

.nav-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

/* 测试结果部分 */
.results-section {
  padding: 20px;
}

.result-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.result-card h2 {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.mbti-type {
  font-size: 36px;
  font-weight: bold;
  color: #4CAF50;
  text-align: center;
  margin: 20px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.type-description {
  text-align: center;
  color: #666;
  margin-bottom: 30px;
  line-height: 1.6;
}

.dimension-analysis {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin: 30px 0;
}

.dimension {
  background: #f9f9f9;
  border-radius: 12px;
  padding: 20px;
}

.dimension h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 16px;
}

.dimension-score {
  margin-bottom: 16px;
}

.score-bar {
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.score-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.score-labels {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.dimension-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.career-suggestions {
  margin-top: 30px;
}

.career-suggestions h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.career-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.career-item {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.career-icon {
  color: #4CAF50;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 30px;
}

.action-btn {
  flex: 1;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn.primary {
  background: #4CAF50;
  color: white;
}

.action-btn.primary:hover {
  background: #45a049;
}

.action-btn.secondary {
  background: #f5f5f5;
  color: #666;
}

.action-btn.secondary:hover {
  background: #e0e0e0;
}

/* 职业匹配分析部分 */
.career-match-section {
  padding: 20px;
}

.career-match-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.personality-traits {
  margin-bottom: 30px;
}

.trait-item {
  background: #f9f9f9;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
}

.trait-item h4 {
  font-size: 18px;
  color: #333;
  margin-bottom: 12px;
}

.career-matches {
  margin-bottom: 30px;
}

.match-item {
  background: #f9f9f9;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
}

.match-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.match-level {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
}

.match-level.高 {
  background: #e8f5e9;
  color: #4CAF50;
}

.match-level.中 {
  background: #fff3e0;
  color: #ff9800;
}

.match-description {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.6;
}

.match-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.match-details h5 {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.match-details ul {
  list-style: none;
  padding: 0;
}

.match-details li {
  color: #666;
  margin-bottom: 8px;
  padding-left: 20px;
  position: relative;
}

.match-details li::before {
  content: "•";
  position: absolute;
  left: 0;
  color: #4CAF50;
}

.development-suggestions {
  margin-top: 30px;
}

.suggestion-item {
  background: #f9f9f9;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
}

.suggestion-item h4 {
  font-size: 18px;
  color: #333;
  margin-bottom: 12px;
}

.option-btn {
  width: 100%;
  padding: 16px;
  margin-bottom: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background: white;
  text-align: left;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-btn:hover {
  border-color: #4CAF50;
  background: #f9f9f9;
}

.option-btn.selected {
  border-color: #2E7D32;
  background: #C8E6C9;
  color: #1B5E20;
  font-weight: bold;
}

.option-btn.previous-answer {
  border-color: #FFA000;
  background: #FFF3E0;
  color: #E65100;
}

/* 添加加载状态样式 */
.loading-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.loading-state p {
  color: #666;
  font-size: 16px;
}

@media (max-width: 768px) {
  .mbti-test-container {
    padding: 16px;
  }
  
  .welcome-card,
  .question-card,
  .result-card,
  .career-match-card {
    padding: 20px;
  }
  
  .question-text {
    font-size: 16px;
  }
  
  .option-btn {
    padding: 12px;
    font-size: 14px;
  }
  
  .dimension-analysis {
    grid-template-columns: 1fr;
  }
  
  .career-grid {
    grid-template-columns: 1fr;
  }
  
  .match-details {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style> 